package top.haijunit.work.core.filter;

import cn.hutool.core.text.CharSequenceUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;
import top.haijunit.work.core.auth.JwtTokenUtils;
import top.haijunit.work.core.doamin.ExceptionEnum;
import top.haijunit.work.core.doamin.Result;
import top.haijunit.work.utils.SpringWebUtils;

import java.io.IOException;

/**
 * 【说明类功能】
 *
 * @author zhanghaijun
 * @since 2024-08-23
 */
@Slf4j
@WebFilter(filterName = "loginAuthFilter", urlPatterns = {"/user/*"})
public class LoginAuthFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(request, response);
        } else {
            final String token = request.getHeader("Authorization");
            if (CharSequenceUtil.isBlank(token) || JwtTokenUtils.isTokenExpired(token)) {
                response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,authorization");
                response.setHeader("Access-Control-Allow-Credentials", "true");

                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                SpringWebUtils.writeJson(response, Result.of(ExceptionEnum.UNAUTHORIZED, "token失效，请重新登录"));
                return;
            }
            Claims claims = JwtTokenUtils.extractAllClaims(token);
            request.setAttribute("username", claims.getSubject());
            request.setAttribute("refreshToken", JwtTokenUtils.refreshToken(token));
            filterChain.doFilter(request, response);
        }
    }
}
